import React, { createContext, useContext, useState, ReactNode } from 'react';
import { ResourceService, Resource } from './services/ResourceService';
import { API_PATHS } from '../../config/apiConfig';

interface Resource {
  id: string;
  title: string;
  description: string;
  type: string;
  size: number;
  uploaderId: string;
  uploaderName: string;
  downloadCount: number;
  shareRatio: number;
  createdAt: string;
  tags: { id: number; name: string }[];
  coverImage: File | null
}

interface ResourceContextType {
  resources: Resource[];
  loading: boolean;
  uploadResource: (file: File, metadata: Partial<Resource>) => Promise<void>;
  downloadResource: (resourceId: string) => Promise<void>;
  searchResources: (query: string) => Promise<Resource[]>;
  getResourceList: (page?: number, pageSize?: number) => Promise<Resource[]>;
}

const ResourceContext = createContext<ResourceContextType | null>(null);

export const useResource = () => {
  const context = useContext(ResourceContext);
  if (!context) {
    throw new Error('useResource must be used within a ResourceProvider');
  }
  return context;
};

interface ResourceProviderProps {
  children: ReactNode;
}

export const ResourceProvider: React.FC<ResourceProviderProps> = ({ children }) => {
  const [resources, setResources] = useState<Resource[]>([]);
  const [loading, setLoading] = useState(false);

  const uploadResource = async (file: File, metadata: Partial<Resource>) => {
    try {
      setLoading(true);
      const formData = new FormData();
      formData.append('file', file); // 种子文件
      formData.append('title', metadata.title || '');
      formData.append('description', metadata.description || '');
      
      
      // 如果有标签，将标签ID合并为逗号分隔的字符串
      if (metadata.tags && metadata.tags.length > 0) {
        // 后端期望接收一个tags参数，包含逗号分隔的标签ID
        const tagIds = metadata.tags.map(tag => tag.id.toString()).join(',');
        formData.append('tags', tagIds);
      }
      
      // 如果有封面图片，添加封面图片
      if (metadata.coverImage) {
        formData.append('coverImage', metadata.coverImage);
      }
      
      // 添加上传者信息
      if (metadata.uploaderId) {
        formData.append('uploaderId', metadata.uploaderId);
      }
      
      if (metadata.uploaderName) {
        formData.append('uploaderName', metadata.uploaderName);
      }

      // 使用fetch直接调用API，因为ResourceService没有处理FormData的方法
      // 注意：当使用FormData时，不要设置Content-Type头，让浏览器自动设置，包含boundary信息
      const response = await fetch(`${API_PATHS.resources}/upload`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          // 不要设置Content-Type头，让浏览器自动设置multipart/form-data和boundary
        },
        body: formData,
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || '资源上传失败');
      }

      const newResource = await response.json();
      setResources(prev => [...prev, newResource]);
      return newResource;
    } catch (error) {
      console.error('上传错误:', error);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const downloadResource = async (resourceId: string) => {
    try {
      setLoading(true);
      // 先支付积分
      await ResourceService.payPoints(resourceId);
      
      // 然后下载资源
      const downloadUrl = await ResourceService.downloadResource(resourceId);
      
      // 打开下载链接
      window.open(downloadUrl, '_blank');
    } catch (error) {
      console.error('下载错误:', error);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const searchResources = async (query: string) => {
    try {
      setLoading(true);
      const response = await ResourceService.queryResources(query);
      setResources(response.records);
      return response.records;
    } catch (error) {
      console.error('搜索错误:', error);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const getResourceList = async (page: number = 1, pageSize: number = 10) => {
    try {
      setLoading(true);
      const response = await ResourceService.getResourceList(page, pageSize);
      setResources(response.records);
      return response.records;
    } catch (error) {
      console.error('获取资源列表错误:', error);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  return (
    <ResourceContext.Provider value={{ resources, loading, uploadResource, downloadResource, searchResources, getResourceList }}>
      {children}
    </ResourceContext.Provider>
  );
};